import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
from super.super import *
class Main(Mysql):
    pass

class WinStart(Main):

    def __init__(self):
        # 登录类初始化
        self.db_connect()
        self.win_init()
    '''窗口初始化'''
    def win_init(self):
        # 初始化
        self.windows1 = tk.Tk()
        self.windows1.config()
        self.windows1.title('登录窗口')
        self.windows1.geometry("350x200")
        # 控件初始化
        self.label = tk.Label(self.windows1, text='请登录', width=20, height=4)
        self.label2 = tk.Label(self.windows1,  text='用户名：', width=20, height=1)
        self.label3 = tk.Label(self.windows1,  text='密码：', width=20, height=1)
        self.entry1 = tk.Entry(self.windows1, bg='Lavender', width=20)
        self.entry2 = tk.Entry(self.windows1, bg='Lavender', width=20)
        self.button = tk.Button(self.windows1, text="登录", bg='Moccasin', width=20, height=1, command=self.get_text_data)
        self.pack()
    def pack(self):
        # 放置控件
        self.label.pack()
        self.label2.place(x=0, y=72)
        self.label3.place(x=0, y=90)
        self.entry1.pack()
        self.entry2.pack()
        self.button.pack()
        self.windows1.mainloop()
    '''获取登录数据'''
    def get_text_data(self):
        uesr = self.entry1.get()
        pwd = self.entry2.get()
        self.select_db('admin')
        data = self.select_all(dict(user=uesr,password=pwd))
        if data:
            print(tk.messagebox.showinfo(title='登录成功', message='密码正确！'))
            self.windows1.destroy()
            MainWin()
        else:
            print(tk.messagebox.showerror(title='出错了！', message='密码错误'))

class MainWin(Main):
    '''总初始化'''
    def __init__(self):
        self.db_connect()
        self.win_init()
    '''窗口初始化'''
    def win_init(self):
        # 窗口初始化
        self.windows2 = tk.Tk()
        self.windows2.title('学生信息管理系统')
        self.windows2.config()
        self.windows2.geometry("400x600")
        self.frame1 = tk.Frame(self.windows2)
        self.frame2 = tk.Frame(self.windows2)#, bg='LightCoral'

        # 控件初始化
        self.tree = ttk.Treeview(self.windows2, show="headings")
        self.tree["columns"] = ("序号",
                                "姓名",
                                "学号"
                                # "年龄",
                                # "性别"
                                )
        # 设置列，列还不显示
        self.tree.column("序号", width=100)
        self.tree.column("姓名", width=100)
        self.tree.column("学号", width=100)
        # tree.column("年龄", width=100)
        # tree.column("性别", width=100)
        # 设置表头
        self.tree.heading("序号", text="序号")
        self.tree.heading("姓名", text="姓名")
        self.tree.heading("学号", text="学号")
        # tree.heading("年龄", text="年龄-age")
        # tree.heading("性别", text="性别-gender")
        self.tree.bind('<ButtonRelease-3>',self.treeviewClick)  # 绑定单击离开事件===========

        self.label1 = tk.Label(self.frame1,  text='请输入查询数据：', width=20, height=1)
        self.text1 = tk.Entry(self.frame1, bg='Lavender', width=20)
        self.button1 = tk.Button(self.frame1, text="查询", bg='Moccasin', width=5, height=1, command=self.get_data)
        self.label12 = tk.Label(self.frame1,  text='请在下方插入学生数据', width=20, height=1)
        self.label13 = tk.Label(self.frame1,  text='姓名：', width=10, height=1)
        self.text2 = tk.Entry(self.frame1, bg='Lavender', width=10)
        self.label14 = tk.Label(self.frame1, text='学号：', width=10, height=1)
        self.text3 = tk.Entry(self.frame1, bg='Lavender', width=10)
        self.label15 = tk.Label(self.frame1, text='密码：', width=10, height=1)
        self.text4 = tk.Entry(self.frame1, bg='Lavender',show='*', width=10)
        self.button2 = tk.Button(self.frame1, text="插入", bg='Moccasin', width=5, height=1, command=self.insert_data)
        self.button3 = tk.Button(self.frame1, text="导出个人信息", bg='Moccasin', width=10, height=1, command=self.output_data)
        self.button4 = tk.Button(self.frame1, text="导出成绩", bg='Moccasin', width=10, height=1, command=self.get_all_grade)
        self.pack1()
        self.windows2.mainloop()
    def pack1(self):
        #放置控件
        self.tree.pack(pady=5)
        self.frame1.place(relwidth=0.99,relheight=0.5,relx=0.01,rely=0.4)
        self.label1.place(relx=0.05,rely=0.01)
        self.text1.place(relx=0.35,rely=0.01)
        self.button1.place(relx=0.75,rely=0.0)
        self.button4.place(relx=0.75, rely=0.2)
        self.button3.place(relx=0.75,rely=0.3)
        self.label12.place(relx=0.0,rely=0.15)
        self.label13.place(relx=0.0,rely=0.25)
        self.text2.place(relx=0.15,rely=0.25)
        self.label14.place(relx=0.0,rely=0.35)
        self.text3.place(relx=0.15,rely=0.35)
        self.label15.place(relx=0.0, rely=0.45)
        self.text4.place(relx=0.15, rely=0.45)
        self.button2.place(relx=0.18,rely=0.55)




    def get_data(self,input=''):
        # 从数据库获取数据
        input=self.text1.get()
        input=dict(name=input,sid=input,Id=input)
        self.select_db('student')
        data=self.select_all(input,op1='LiKE',op2='OR')
        self.clear(self.tree)
        for stu_data in data:
            tmp=[]
            for each in stu_data:
                tmp.append(stu_data[each])
            tuple_data = tuple(tmp)
            self.tree.insert("",0,values=tuple_data)#插入到表格中
            tmp.clear()
        self.tmp_data=data
        self.text1.delete('0','end')
    def insert_data(self):
        # 插入数据
        name = self.text2.get()
        sid = self.text3.get()
        pwd = self.text4.get()
        self.select_db('student')
        try:
            self.insert_data_one(dict(name=name,sid=sid,pwd=pwd))
        except BaseException as e:
            self.rollback()
            print(tk.messagebox.showerror(title='出错了！', message='sql错误'+str(e)))
        self.get_data(name)
        self.text2.delete('0','end')
        self.text3.delete('0','end')
        self.text4.delete('0','end')

    def treeviewClick(self,event):
        # 右击表格事件（删除操作）
        if tk.messagebox.askyesno('确认删除？', '确定删除？', icon='warning'):
            self.select_db('student')
            items = self.tree.selection()
            list=[]
            for item in items:
                item_value = self.tree.item(item, 'values')
                Id = item_value[0]
                list.append(Id)
            try:
                try:
                    for Id in list:
                        self.delete_one(dict(Id=Id))
                except:
                    self.rollback()
                    print(tk.messagebox.showerror(title='出错了！', message='sql错误'))
                else:
                    tk.messagebox.showinfo('删除成功','删除成功！')
                    self.get_data()
            except BaseException as e:
                print("错误类型：",e)


    def output_data(self):
        #将学生信息批量导入到excel中
        self.select_db('student')
        error_num = 0
        file = 'person.xlsx'
        for list1 in self.tmp_data:
            try:
                Super().save_person_data(list1['sid'], list1['pwd'], file)
            except:
                error_num += 1
        if error_num != 0:
            tk.messagebox.showinfo('导出完成', '导出到' + file + '失败' + str(error_num) + '个')
        else:
            tk.messagebox.showinfo('导出完成', '全部成功')
    def get_all_grade(self):
        #批量获取学生的成绩
        self.select_db('student')
        error_num=0
        file='grade.xlsx'
        for list1 in self.tmp_data:
            try:
                Super().save_grade(list1['sid'],list1['pwd'],file)
            except:
                error_num+=1
        if error_num!=0:
            tk.messagebox.showinfo('导出完成', '导出到'+file+'失败'+str(error_num)+'个')
        else:
            tk.messagebox.showinfo('导出完成', '全部成功')
    @classmethod
    def clear(cls,tree1):
        x=tree1.get_children()
        for item in x:
            tree1.delete(item)
